import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'dart:async';
import 'package:async/async.dart';
import '../../donggudi_component/theme_list/listitem.dart';
import '../../platform/PlatformApi.dart';


class TicaiList extends StatefulWidget {
  final Map<String, String> parameters;

  TicaiList({required this.parameters});

  @override
  _TicaiListPageState createState() => _TicaiListPageState();
}

class _TicaiListPageState extends State<TicaiList> with WidgetsBindingObserver {
  static const MethodChannel _channel = MethodChannel('ViewApi');
  final int initialItemCount = 10;
  List<Map<String, dynamic>> _visibleTopics = [];
  List<Map<String, dynamic>> _allTopics = [];
  bool _jiazai = false;
  bool _heiye = false;
  String? _riqi;
  String? _zuixiaoriqi;
  String? _zuidariqi;
  DateTime? _selectedDate;
  bool isEmbedded = false;
  int? _refreshTime;
  Timer? _refreshTimer;
  int? _zhishuRefreshTime;
  Timer? _zhishuRefreshTimer;
  Map<String, dynamic>? _firstZhishuData;
  bool _isDataLoaded = false; // 标记数据是否加载完成
  late ScrollController _scrollController;
  double _scrollOffset = 0.0;
  int _yema = 1; // 当前页码
  bool _gengduoshuju = true; // 是否有更多数据

  bool _zhengzaijiazai = false;
  bool _qingqiuzanting = false;
  late CancelableOperation _fetchOperation;

  @override
  void initState() {
    super.initState();
    // 初始化滚动控制器并监听滚动状态
    _scrollController = ScrollController();
    _scrollController.addListener(() {
      _scrollOffset = _scrollController.offset;
    });

    // 恢复夜间模式状态
    final String? isNightMode = widget.parameters['isNightMode'];
    _heiye = (isNightMode == "1");

    // 设置状态栏样式
    SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
      statusBarColor: Colors.transparent,
      statusBarIconBrightness: _heiye ? Brightness.dark : Brightness.light,
    ));

    // 初始化日期参数
    _liebiaoshuju().then((_) {
      // 初始化 `_selectedDate`
      if (_riqi != null && _shifouyouxiao(_riqi!)) {
        _selectedDate = DateTime.parse(_riqi!); // 使用传入的 `day` 初始化
      } else if (_zuidariqi != null && _shifouyouxiao(_zuidariqi!)) {
        _selectedDate = DateTime.parse(_zuidariqi!); // 使用后端返回的最大日期
      }


      // 其他初始化逻辑
      _jiazaishuju();
      _zidongshuaxin();
    });

    // 设置 MethodChannel 的事件监听
    _channel.setMethodCallHandler((call) async {
      try {
        if (call.method == 'onPageVisibleChange') {
          final bool isVisible = call.arguments as bool;
          print("收到 onPageVisibleChange: $isVisible");
          _tingzhishuaxin(isVisible);
        } else {
          print("未处理的方法: ${call.method}");
        }
      } catch (e) {
        print("处理 onPageVisibleChange 时发生错误: $e");
      }
    });

    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    // 保存当前滚动位置和分页参数
    widget.parameters['scrollOffset'] = _scrollOffset.toString();
    widget.parameters['page'] = _yema.toString();
    widget.parameters['day'] = _riqi ?? '';

    _zantingqingqiu();
    _scrollController.dispose();
    WidgetsBinding.instance.removeObserver(this);

    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed) {
      // 应用进入前台，判断当前页面是否是可见页面
      if (ModalRoute.of(context)?.isCurrent == true) {
        _tingzhishuaxin(true);
      }
    } else if (state == AppLifecycleState.paused) {
      // 应用进入后台
      _tingzhishuaxin(false);
    }
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();

    final ModalRoute? route = ModalRoute.of(context);
    if (route?.isCurrent == true) {
      print("页面变为可见时的参数: ${widget.parameters}");
      _tingzhishuaxin(true); // 页面可见时恢复自动刷新
    } else {
      print("页面离开时的参数: ${widget.parameters}");
      _tingzhishuaxin(false); // 页面不可见时暂停自动刷新
    }
  }

  void _zidongshuaxin() {
    _qingqiuzanting = false;

    // 恢复时检查最新的夜间模式状态
    _heiyezhuangtai();
    if (_refreshTime != null && _refreshTime! > 0) {
      _kaishishuaxin();
    }

    if (_zhishuRefreshTime != null && _zhishuRefreshTime! > 0) {
      _shangzhengshuaxin();
    }

    _jiazaishuju();
  }

  void _zantingqingqiu() {
    _qingqiuzanting = true;
    _refreshTimer?.cancel(); // 停止主题列表的定时刷新
    _zhishuRefreshTimer?.cancel(); // 停止上证指数的定时刷新
    _quxiaoqingqiu(); // 取消当前正在进行的网络请求
    print("自动刷新已停止，页面不再请求数据。");
  }

  //黑夜模式状态获取
  Future<void> _heiyezhuangtai() async {
    try {
      // 调用安卓接口获取最新的夜间模式状态
      final String isNightMode = await _channel.invokeMethod('isNightMode');
      setState(() {
        _heiye = isNightMode == "1"; // "1" 表示夜间模式
      });

      // 动态更新状态栏样式
      SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
        statusBarColor: Colors.transparent,
        statusBarIconBrightness: _heiye ? Brightness.dark : Brightness.light,
      ));

      print("isNightMode: $_heiye");
    } on PlatformException catch (e) {
      print("Failed to get isNightMode: '${e.message}'");
    }
  }

  // 加载所有数据的方法
  Future<void> _jiazaishuju() async {
    setState(() {
      _isDataLoaded = false; // 数据加载中
    });

    await Future.wait([
      _liebiaoshuju(),
      _shangzhengshuju(),
    ]);

    // 数据加载完成后恢复滚动位置
    if (_scrollOffset > 0.0) {
      Future.delayed(Duration(milliseconds: 200), () {
        _scrollController.jumpTo(_scrollOffset);
      });
    }

    setState(() {
      _isDataLoaded = true; // 数据加载完成
    });
  }

  void _riqifanwei(Map<String, dynamic> data) {
    setState(() {
      _zuixiaoriqi = data['min_day']; // 从后端获取的最小日期
      _zuidariqi = data['max_day']; // 从后端获取的最大日期
      _riqi = widget.parameters['day'] ?? data['day']; // 页面参数优先，否则使用后端返回的当前日期
    });
  }

  //接口调用，获取列表数据
  Future<void> _liebiaoshuju() async {
    if (_zhengzaijiazai || _qingqiuzanting || !_gengduoshuju) return;

    setState(() {
      _zhengzaijiazai = true;
    });

    final String pageCount = (_yema * 10).toString(); // 动态计算总条数

    print("【${DateTime.now()}】开始加载数据，页码: $_yema，总条数: $pageCount, refresh_time: $_refreshTime");

    try {
      final response = await PlatformApi.netApi(
        '/bk/rank/ticai',
        {
          'page': '1', // 始终从第一页开始
          'pagecount': pageCount,
          'day': _riqi ?? '',
        },
        PlatformApi.HttpMethodGet,
      );

      if (response != null) {
        final Map<String, dynamic> data = json.decode(response);

        if (data['code'] == 10000 && data['data'] != null) {
          _riqifanwei(data['data']); // 初始化日期范围

          final List<Map<String, dynamic>> newTopics = List<Map<String, dynamic>>.from(data['data']['list']);

          setState(() {
            _allTopics = newTopics;
            _visibleTopics = List.from(_allTopics);
            _gengduoshuju = newTopics.length >= int.parse(pageCount);
            _refreshTime = data['data']['refresh_time'] ?? 0;

            print("从接口获取的 refresh_time 值: $_refreshTime");
          });

          if (_refreshTime != null && _refreshTime! > 0) {
            _kaishishuaxin();
          } else {
            print("refresh_time 值无效或未设置，无法启动自动刷新");
          }

          print("【${DateTime.now()}】数据加载完成，总条数: ${_visibleTopics.length}");
        } else {
          print("【${DateTime.now()}】数据加载失败，返回数据为空或无效");
        }
      }
    } catch (e) {
      print("【${DateTime.now()}】加载数据时发生错误: $e");
    } finally {
      setState(() {
        _zhengzaijiazai = false;
        print("【${DateTime.now()}】结束数据加载, _zhengzaijiazai: $_zhengzaijiazai");
      });
    }
  }

  bool _shifouyouxiao(String? date) {
    if (date == null || date.isEmpty) return false;
    try {
      DateTime.parse(date); // 尝试解析日期
      return true; // 如果解析成功，返回 true
    } catch (e) {
      return false; // 捕获异常，返回 false
    }
  }

  //调用接口，获取上证指数数据
  Future<void> _shangzhengshuju() async {
    try {
      final CancelableOperation fetchOperation = CancelableOperation.fromFuture(
        PlatformApi.netApi(
          '/app/stock/zhishu',
          {},
          PlatformApi.HttpMethodGet,
        ),
        onCancel: () {
          print("Request to /app/stock/zhishu has been cancelled");
        },
      );

      final response = await fetchOperation.value;
      if (response != null) {
        final Map<String, dynamic> data = json.decode(response);
        print('Fetched data from /app/stock/zhishu: $data');

        setState(() {
          _firstZhishuData = data['data']['zs_list'][0];
          _zhishuRefreshTime = data['data']['refresh_time'];
        });

        if (_zhishuRefreshTime != null && _zhishuRefreshTime! > 0) {
          _shangzhengshuaxin();
        }
      }
    } catch (e) {
      print('Error calling /app/stock/zhishu: $e');
    }
  }

  void _kaishishuaxin() {
    _refreshTimer?.cancel(); // 清除之前的定时器

    if (_refreshTime != null && _refreshTime! > 0) {
      print("自动刷新已开启，刷新间隔: $_refreshTime 秒");

      _refreshTimer = Timer.periodic(Duration(seconds: _refreshTime!), (timer) {
        if (!_zhengzaijiazai) {
          print("【${DateTime.now()}】实时刷新触发，当前已展示条数: ${_visibleTopics.length}");
          _huifushuaxin(); // 调用刷新已展示数据的方法
        } else {
          print("【${DateTime.now()}】跳过本次刷新，因为数据正在加载中");
        }
      });
    }
  }

  Future<void> _huifushuaxin() async {
    if (_qingqiuzanting) return;

    print("【${DateTime.now()}】开始刷新所有已展示数据...");
    try {
      // 计算当前展示的总条数（基于分页逻辑）
      final int totalItemCount = _yema * 10;

      final response = await PlatformApi.netApi(
        '/bk/rank/ticai',
        {
          'page': '1', // 始终从第一页开始请求
          'pagecount': totalItemCount.toString(), // 请求所有已展示的数据
          'day': _riqi ?? '', // 当前选中的日期
        },
        PlatformApi.HttpMethodGet,
      );

      if (response != null) {
        final Map<String, dynamic> data = json.decode(response);

        if (data['code'] == 10000 && data['data'] != null && data['data'].containsKey('list')) {
          final List<Map<String, dynamic>> refreshedTopics = List<Map<String, dynamic>>.from(data['data']['list']);

          setState(() {
            // 更新所有已展示的数据
            _allTopics = refreshedTopics;
            _visibleTopics = List.from(_allTopics);

            print("【${DateTime.now()}】实时刷新完成，总条数: ${_visibleTopics.length}");
          });
        } else {
          print("【${DateTime.now()}】实时刷新失败，返回数据为空或无效");
        }
      }
    } catch (e) {
      print("【${DateTime.now()}】实时刷新时发生错误: $e");
    }
  }


  //停止自动刷新
  void _tingzhishuaxin(bool isVisible) {
    if (isVisible) {
      print("【${DateTime.now()}】页面可见，恢复自动刷新");
      _zidongshuaxin(); // 恢复自动刷新
    } else {
      print("【${DateTime.now()}】页面不可见，暂停自动刷新");
      _zantingqingqiu(); // 停止自动刷新
    }
  }

  // 上证指数自动刷新
  void _shangzhengshuaxin() {
    _zhishuRefreshTimer?.cancel();
    _zhishuRefreshTimer =
        Timer.periodic(Duration(seconds: _zhishuRefreshTime!), (timer) {
          if (mounted && !_qingqiuzanting) {
            _shangzhengshuju();
          } else {
            timer.cancel();
          }
        });
  }

  void _quxiaoqingqiu() {
    if (_zhengzaijiazai) {
      _fetchOperation.cancel();
      setState(() {
        _zhengzaijiazai = false;
      });
      print('Request has been cancelled.');
    }
  }

  void _riqixuanze() async {
    print("Starting date selection");
    try {
      if (_zuixiaoriqi == null || _zuidariqi == null) {
        print("时间范围未正确初始化: _minDay=$_zuixiaoriqi, _maxDay=$_zuidariqi");
        return;
      }

      // 确保时间范围的顺序正确
      String minDay = _zuixiaoriqi!;
      String maxDay = _zuidariqi!;
      if (DateTime.parse(minDay).isAfter(DateTime.parse(maxDay))) {
        final temp = minDay;
        minDay = maxDay;
        maxDay = temp;
      }

      // 构造时间选择器所需的参数
      final Map<String, String> dateParams = {
        'min_day': minDay,
        'max_day': maxDay,
        'day': _riqi ?? maxDay,
      };
      final String jsonString = json.encode(dateParams);
      print("发送到原生时间选择器的参数: $jsonString");

      // 调用原生方法选择时间
      final String dateString = await _channel.invokeMethod('selectDate', jsonString);
      print("原生时间选择器返回的日期: $dateString");

      // 更新选中的日期并刷新数据
      setState(() {
        _selectedDate = DateTime.parse(dateString);
        _riqi = "${_selectedDate!.year.toString()}${_selectedDate!.month.toString().padLeft(2, '0')}${_selectedDate!.day.toString().padLeft(2, '0')}";
        widget.parameters['day'] = _riqi!;

        _scrollController.jumpTo(0.0); // 滚动到顶部
      });

      // 刷新数据
      _liebiaoshuju();
    } catch (e) {
      print("选择失败: $e");
    }
  }

  @override
  Widget build(BuildContext context) {
    final bottomPadding = MediaQuery.of(context).padding.bottom;

    // 如果数据未加载完成，显示加载指示器
    if (!_isDataLoaded) {
      return Scaffold(
        appBar: null,
        body: Center(child: CircularProgressIndicator()), // 显示加载指示器
      );
    }

    return Scaffold(
      appBar: null,
      body: Padding(
        padding: EdgeInsets.only(bottom: bottomPadding),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            _goujianriqixuanze(),
            Expanded(child: _zhutiliebiao()),
          ],
        ),
      ),
    );
  }

  Future<void> _shanggeriqi() async {
    try {
      final String? availableDatesJson = await _channel.invokeMethod('getTradingData');
      if (availableDatesJson == null || availableDatesJson.isEmpty) {
        print('安卓端返回空数据');
        return;
      }
      final Map<String, dynamic> availableDates = json.decode(availableDatesJson)['list'];
      if (_selectedDate == null) {
        print('当前没有选中的日期');
        return;
      }

      // 检查是否是最小日期
      if (_riqi == _zuixiaoriqi) {
        print('当前选中日期已是最小日期，不可点击');
        return;
      }

      final int currentYear = _selectedDate!.year;
      final int currentMonth = _selectedDate!.month;
      final int currentDay = _selectedDate!.day;

      final Map<String, dynamic>? yearData = availableDates[currentYear.toString()];
      if (yearData == null) {
        print('当前年份的数据不可用');
        return;
      }

      final List<dynamic>? monthData = yearData[currentMonth.toString()];
      if (monthData == null) {
        print('当前月份的数据不可用');
        return;
      }

      // 检查是否是本月第一个可用日期
      bool isFirstAvailableDay = true;
      for (int day = 0; day < currentDay - 1; day++) {
        if (monthData[day] == 1) {
          isFirstAvailableDay = false;
          break;
        }
      }

      if (isFirstAvailableDay) {
        // 选中上个月最后一个可用日期
        int previousMonth = currentMonth - 1;
        int previousYear = currentYear;

        if (previousMonth == 0) {
          previousMonth = 12;
          previousYear--;
        }

        final Map<String, dynamic>? previousYearData = availableDates[previousYear.toString()];
        if (previousYearData == null) {
          print('上一个年份的数据不可用');
          return;
        }

        final List<dynamic>? previousMonthData = previousYearData[previousMonth.toString()];
        if (previousMonthData == null) {
          print('上一个月份的数据不可用');
          return;
        }

        for (int day = previousMonthData.length - 1; day >= 0; day--) {
          if (previousMonthData[day] == 1) {
            setState(() {
              _selectedDate = DateTime(previousYear, previousMonth, day + 1);
              _riqi = "${_selectedDate!.year.toString()}${_selectedDate!.month.toString().padLeft(2, '0')}${_selectedDate!.day.toString().padLeft(2, '0')}";
              widget.parameters['day'] = _riqi!;

              // 重置分页状态
              _yema = 1;
              _gengduoshuju = true;
              _allTopics.clear();
              _visibleTopics.clear();
              _scrollController.jumpTo(0.0); // 滚动到顶部
            });

            // 重新加载数据
            _liebiaoshuju();
            return;
          }
        }
        print('上一个月份没有可用的日期');
        return;
      }

      // 当前选中不是本月第一个可用日期，继续查找当前月份的上一天
      for (int day = currentDay - 2; day >= 0; day--) {
        if (monthData[day] == 1) {
          setState(() {
            _selectedDate = DateTime(currentYear, currentMonth, day + 1);
            _riqi = "${_selectedDate!.year.toString()}${_selectedDate!.month.toString().padLeft(2, '0')}${_selectedDate!.day.toString().padLeft(2, '0')}";
            widget.parameters['day'] = _riqi!;

            // 重置分页状态
            _yema = 1;
            _gengduoshuju = true;
            _allTopics.clear();
            _visibleTopics.clear();
            _scrollController.jumpTo(0.0); // 滚动到顶部
          });

          // 重新加载数据
          _liebiaoshuju();
          return;
        }
      }

      print('当前月份没有可用的上一天');
    } catch (e) {
      print('Error fetching trading data: $e');
    }
  }

  Future<void> _xiageriqi() async {
    try {
      final String? availableDatesJson = await _channel.invokeMethod('getTradingData');
      if (availableDatesJson == null || availableDatesJson.isEmpty) {
        print('安卓端返回空数据');
        return;
      }
      final Map<String, dynamic> availableDates = json.decode(availableDatesJson)['list'];
      if (_selectedDate == null) {
        print('当前没有选中的日期');
        return;
      }

      // 检查是否是最大日期
      if (_riqi == _zuidariqi) {
        print('当前选中日期已是最大日期，不可点击');
        return;
      }

      final int currentYear = _selectedDate!.year;
      final int currentMonth = _selectedDate!.month;
      final int currentDay = _selectedDate!.day;

      final Map<String, dynamic>? yearData = availableDates[currentYear.toString()];
      if (yearData == null) {
        print('当前年份的数据不可用');
        return;
      }

      final List<dynamic>? monthData = yearData[currentMonth.toString()];
      if (monthData == null) {
        print('当前月份的数据不可用');
        return;
      }

      // 查找当前月份的下一个可用日期
      for (int day = currentDay; day < monthData.length; day++) {
        if (monthData[day] == 1) {
          setState(() {
            _selectedDate = DateTime(currentYear, currentMonth, day + 1);
            _riqi = "${_selectedDate!.year.toString()}${_selectedDate!.month.toString().padLeft(2, '0')}${_selectedDate!.day.toString().padLeft(2, '0')}";
            widget.parameters['day'] = _riqi!;

            // 重置分页状态
            _yema = 1;
            _gengduoshuju = true;
            _allTopics.clear();
            _visibleTopics.clear();
            _scrollController.jumpTo(0.0); // 滚动到顶部
          });

          // 重新加载数据
          _liebiaoshuju();
          return;
        }
      }

      // 如果当前月份没有可用的下一天，跳转到下一个月份的第一个可用日期
      int nextMonth = currentMonth + 1;
      int nextYear = currentYear;

      if (nextMonth > 12) {
        nextMonth = 1;
        nextYear++;
      }

      final Map<String, dynamic>? nextYearData = availableDates[nextYear.toString()];
      if (nextYearData == null) {
        print('下一个年份的数据不可用');
        return;
      }

      final List<dynamic>? nextMonthData = nextYearData[nextMonth.toString()];
      if (nextMonthData == null) {
        print('下一个月份的数据不可用');
        return;
      }

      for (int day = 0; day < nextMonthData.length; day++) {
        if (nextMonthData[day] == 1) {
          setState(() {
            _selectedDate = DateTime(nextYear, nextMonth, day + 1);
            _riqi = "${_selectedDate!.year.toString()}${_selectedDate!.month.toString().padLeft(2, '0')}${_selectedDate!.day.toString().padLeft(2, '0')}";
            widget.parameters['day'] = _riqi!;

            // 重置分页状态
            _yema = 1;
            _gengduoshuju = true;
            _allTopics.clear();
            _visibleTopics.clear();
            _scrollController.jumpTo(0.0); // 滚动到顶部
          });

          // 重新加载数据
          _liebiaoshuju();
          return;
        }
      }

      print('下一个月份没有可用的日期');
    } catch (e) {
      print('Error fetching trading data: $e');
    }
  }

  // 指数跳转方法
  void _zhishutiaozhuan() {
    final String? code = _firstZhishuData?['param']?['code'];
    if (code == null) {
      print("Code not found in _firstZhishuData");
      return;
    }
    final Map<String, dynamic> routeParam = {
      "type": "native",
      "url": "/zixuan/0/dapan/detail",
      "param": {
        "code": code, // 从接口数据中获取的 code
        "time_type": widget.parameters['time_type'] ?? "D", // 使用题材列表中的 time_type
        "tab": widget.parameters['tab'] ?? 6 // 使用题材列表中的 tab
      },
    };
    PlatformApi.routeApi(routeParam);
  }

  Widget _goujianriqixuanze() {
    DateTime? displayDate;
    try {
      if (_selectedDate != null) {
        displayDate = _selectedDate!;
      } else if (_riqi != null && _shifouyouxiao(_riqi!)) {
        displayDate = DateTime.parse(_riqi!);
      } else if (_zuidariqi != null && _shifouyouxiao(_zuidariqi!)) {
        displayDate = DateTime.parse(_zuidariqi!); // 使用最后一个可用日期
      } else {
        displayDate = DateTime(2014, 11, 25); // 备用的默认日期
      }
    } catch (e) {
      print("Invalid date format encountered : $e");
      displayDate = DateTime(2014, 11, 25); // 使用默认日期以防止崩溃
    }

    return Container(
      decoration: BoxDecoration(
        color: _heiye ? Colors.black : Colors.white,
        border: Border(
          bottom: BorderSide(
            color: _heiye ? Colors.grey[800]! : Colors.grey[300]!,
            width: 1,
          ),
        ),
      ),
      child: Row(
        children: [
          // 左侧部分，包含“上证指数”等信息
          Expanded(
            child: GestureDetector(
              onTap: _zhishutiaozhuan,
              child: Container(
                padding: EdgeInsets.symmetric(vertical: 1),
                height: 45, // 设置高度
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      _firstZhishuData?['name'] ?? "上证指数",
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                        color: _heiye ? Colors.white : Colors.black,
                        height: 1.0,
                      ),
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Text(
                          _firstZhishuData?['price'],
                          style: TextStyle(
                            color: Colors.green,
                            fontSize: 12,
                            fontWeight: FontWeight.w400,
                          ),
                        ),
                        SizedBox(width: 3),
                        Text(
                          _firstZhishuData?['p_change'] ?? '',
                          style: TextStyle(
                            color: (_firstZhishuData?['p_change'] ?? '').contains('+')
                                ? Color(0xFFF2233B)
                                : (_firstZhishuData?['p_change'] ?? '').contains('-')
                                ? Color(0xFF1CAA3C)
                                : Colors.black,
                            fontSize: 12,
                          ),
                        ),

                        SizedBox(width: 3),
                        Text(
                          " ${_firstZhishuData?['up_cnt']} ",
                          style: TextStyle(
                            color: Colors.red,
                            fontSize: 12,
                          ),
                        ),
                        Text(
                          ":",
                          style: TextStyle(
                            color: _heiye ? Colors.white : Colors.black,
                          ),
                        ),
                        Text(
                          "${_firstZhishuData?['down_cnt'] ?? 0}",
                          style: TextStyle(
                            color: Colors.green,
                            fontSize: 12,
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ),
          // 日期选择部分，包含左右箭头和日期
          Expanded(
            child: Container(
              height: 45,
              decoration: BoxDecoration(
                color: _heiye ? Colors.black : Colors.white,
                border: Border(
                  left: BorderSide(
                    color: _heiye ? Colors.grey[700]! : Colors.grey[300]!,
                    width: 1,
                  ),
                ),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  GestureDetector(
                    onTap: _shanggeriqi,
                    child: Container(
                      width: 25, // 设置独立的固定宽度
                      height: 30, // 设置高度
                      alignment: Alignment.center, // 居中对齐图标
                      decoration: BoxDecoration(
                        border: Border.all(
                          color: _heiye ? Colors.grey[700]! : Color(0xFFE6E6E6),
                          width: 1,
                        ),
                      ),
                      child: Image.asset(
                        _heiye ? 'donggudiicon/icon/baizuojian.png' : 'donggudiicon/icon/heizuojian.png',
                        width: 10,
                      ),
                    ),
                  ),
                  GestureDetector(
                    onTap: _riqixuanze,
                    child: Container(
                      height: 30,
                      decoration: BoxDecoration(
                        color: _heiye ? Colors.black : Colors.white,
                        border: Border(
                          top: BorderSide(
                            color: _heiye ? Colors.grey[700]! : Colors.grey[300]!,
                            width: 1,
                          ),
                          bottom: BorderSide(
                            color: _heiye ? Colors.grey[700]! : Color(0xFFE6E6E6),
                            width: 1,
                          ),
                        ),
                      ),
                      padding: EdgeInsets.symmetric(horizontal: 10), // 设置左右边距自动调整
                      alignment: Alignment.center, // 居中对齐内容
                      child: Text(
                        "${displayDate.year}-${displayDate.month.toString().padLeft(2, '0')}-${displayDate.day.toString().padLeft(2, '0')}",
                        style: TextStyle(
                          fontSize: 15,
                          color: _heiye ? Colors.white : Colors.black,
                        ),
                      ),
                    ),
                  ),
                  GestureDetector(
                    onTap: _xiageriqi,
                    child: Container(
                      width: 25,
                      height: 30,
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        border: Border.all(
                          color: _heiye ? Colors.grey[700]! : Color(0xFFE6E6E6),
                          width: 1,
                        ),
                      ),
                      child: Image.asset(
                        _heiye ? 'donggudiicon/icon/baiyoujian.png' : 'donggudiicon/icon/heiyoujian.png',
                        width: 10,
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _zhutiliebiao() {
    return Container(
      color: _heiye ? Colors.black : Colors.white,
      child: NotificationListener<ScrollNotification>(
        onNotification: (ScrollNotification scrollInfo) {
          if (!_jiazai &&
              scrollInfo.metrics.pixels == scrollInfo.metrics.maxScrollExtent &&
              _gengduoshuju) {
            _loadMoreItems(); // 触底加载更多
          }

          // 添加滑动日志打印
          if (scrollInfo is ScrollUpdateNotification) {
            print("滚动 Offset: ${scrollInfo.metrics.pixels}");
          } else if (scrollInfo is ScrollStartNotification) {
            print("滚动开始于: ${scrollInfo.metrics.pixels}");
          } else if (scrollInfo is ScrollEndNotification) {
            print("滚动结束于: ${scrollInfo.metrics.pixels}");
          }

          return false;
        },
        child: ListView.builder(
          controller: _scrollController,
          padding: EdgeInsets.zero,
          itemCount: _visibleTopics.length + 1,
          itemBuilder: (context, index) {
            if (index == _visibleTopics.length) {
              return _jiazai
                  ? Center(
                child: Padding(
                  padding: EdgeInsets.all(16.0),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      // 缩小的 CircularProgressIndicator
                      SizedBox(
                        width: 16.0, // 设置动画的宽度
                        height: 16.0, // 设置动画的高度
                        child: CircularProgressIndicator(
                          strokeWidth: 2.0, // 缩小圆圈的宽度
                          color: _heiye ? Colors.white : Colors.grey, // 根据模式设置颜色
                        ),
                      ),
                      SizedBox(width: 8.0), // 动画和文字之间的间距
                      // 加载文字
                      Text(
                        "正在加载",
                        style: TextStyle(
                          fontSize: 14.0, // 调整文字大小
                          color: _heiye ? Colors.white : Colors.grey, // 根据模式设置颜色
                        ),
                      ),
                    ],
                  ),
                ),
              )
                  : SizedBox.shrink();
            }

            final topic = _visibleTopics[index];
            final Map<String, dynamic> routeParam = topic['param'] as Map<String, dynamic>;

            return GestureDetector(
              onTap: () => _tiaozhuan(context, routeParam),
              child: Listitem(
                topic: topic,
                shifouheiye: _heiye,
                index: index,
              ),
            );
          },
        ),
      ),
    );
  }


  Future<String?> _kejianxing() async {
    try {
      print("调用安卓端 onPageVisibleChange 方法...");
      final String? status = await _channel.invokeMethod('onPageVisibleChange');
      print("安卓端返回 onPageVisibleChange: $status");
      return status;
    } catch (e) {
      print("调用 onPageVisibleChange 方法时发生错误: $e");
      return null;
    }
  }

  @override
  void didUpdateWidget(covariant TicaiList oldWidget) {
    super.didUpdateWidget(oldWidget);
    print("didUpdateWidget 被调用");
    if (oldWidget.parameters != widget.parameters) {
      print("parameters 发生变化，检查页面可见性...");
      _checkPageVisibilityAndUpdate();
    }
  }

  Future<void> _checkPageVisibilityAndUpdate() async {
    print("检查页面可见性...");
    final String? onPageVisibleChange = await _kejianxing();
    if (onPageVisibleChange == null) {
      print("onPageVisibleChange 返回空值");
      return;
    }
    final bool isVisible = onPageVisibleChange == "true";
    print("页面可见性: $isVisible");
    _tingzhishuaxin(isVisible);
  }

  void _loadMoreItems() {
    if (!_zhengzaijiazai && _gengduoshuju) {
      print("【${DateTime.now()}】触底加载更多数据，当前页码: $_yema");

      setState(() {
        _jiazai = true;
        _yema++; // 增加页码
      });

      _liebiaoshuju().then((_) {
        setState(() {
          _jiazai = false; // 加载完成后关闭加载状态
        });

        // 重新触发实时刷新，更新所有已展示的数据
        print("【${DateTime.now()}】加载更多数据完成，当前总条数: ${_visibleTopics.length}");
        _huifushuaxin();
      });
    }
  }

  void _tiaozhuan(
      BuildContext context, Map<String, dynamic> routeParam) {
    PlatformApi.routeApi(routeParam);
  }
}
